<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/10 0010
 * Time: 下午 16:15
 */
namespace frontend\components\behaviors;

use common\models\c2\entity\FeUserModel;
use common\models\c2\statics\FeUserType;
use Yii;
use yii\base\ActionFilter;

class WechatAuthBehavior extends ActionFilter
{

    public function beforeAction($action)
    {
        // 微信网页授权:
        if(!Yii::$app->wechat->isAuthorized()) {
            // Yii::info('在微信客户端');
            // return Yii::$app->wechat->authorizeRequired()->send();
            return Yii::$app->wechat->authorizeRequired()->send();
        }
        if (Yii::$app->user->isGuest) {
            $wechatUser = Yii::$app->wechat->getUser();
            $feUser = FeUserModel::findOne(['open_id' => $wechatUser->openid]);
            $attrs = [
                'type' => FeUserType::TYPE_WECHAT_REGISTRATION,
                'open_id' => $wechatUser->openid,
                'wechat_open_id' => $wechatUser->openid,
                'username' => $wechatUser->nickname,
                'registration_ip' => Yii::$app->request->userIP,
                'last_login_ip' => Yii::$app->request->userIP,
                'unconfirmed_email' => $wechatUser->avatar,
            ];
            if (!$feUser) {
                $feUser = new FeUserModel();
                $feUser->loadDefaultValues();
                $feUser->setAttributes($attrs);
                $feUser->save();
            }
            Yii::$app->user->login($feUser, 60 * 60 * 24);
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function afterAction($action, $result)
    {
        return parent::afterAction($action, $result); // TODO: Change the autogenerated stub
    }
}